<%--
  Created by IntelliJ IDEA.
  User: 欧阳佳新
  Date: 2024/12/24
  Time: 08:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: Arial, Helvetica, sans-serif;
        }
        .cart-container {
            max-width: 1200px;
            margin: 20px auto;
            display: flex;
            flex-wrap: nowrap;
            gap: 20px;
        }
        .cart-items {
            flex: 1 1 auto;
            max-height: 80vh;
            overflow-y: auto;
            padding-right: 10px;
        }
        .cart-item {
            border-bottom: 1px solid #ddd;
            padding: 15px 0;
        }
        .cart-item img {
            max-width: 100px;
            cursor: pointer;
        }
        .cart-item-title {
            font-size: 16px;
            font-weight: bold;
        }
        .cart-item-spec {
            color: #6c757d;
        }
        .cart-summary {
            flex: 0 0 300px;
            background-color: white;
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 5px;
            position: sticky;
            top: 20px;
            height: fit-content;
        }
        .btn-checkout {
            background-color: orange;
            color: white;
            font-size: 18px;
            width: 100%;
        }
        .btn-checkout:hover {
            background-color: #e69500;
        }
        .btn-danger {
            background-color: red;
            color: white;
        }
        .cart-item img {
            max-width: 100px;
            border-radius: 8px;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            cursor: pointer;
        }
        .cart-item img:hover {
            transform: scale(1.2);
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
        }
    </style>
</head>
<body>
<%--<nav class="navbar navbar-expand-lg navbar-light bg-light">--%>
<%--    <div class="container-fluid">--%>
<%--        <a class="navbar-brand" href="#">电商平台</a>--%>
<%--        <div class="collapse navbar-collapse">--%>
<%--            <ul class="navbar-nav me-auto">--%>
<%--                <li class="nav-item"><a class="nav-link" href="#">首页</a></li>--%>
<%--                <li class="nav-item"><a class="nav-link" href="#">我的订单</a></li>--%>
<%--                <li class="nav-item"><a class="nav-link" href="#">收藏夹</a></li>--%>
<%--                <li class="nav-item"><a class="nav-link" href="#">商品分类</a></li>--%>
<%--                <li class="nav-item"><a class="nav-link" href="#">客户服务</a></li>--%>
<%--            </ul>--%>
<%--            <ul class="navbar-nav">--%>
<%--                <li class="nav-item"><a class="nav-link" href="#">登录 / 注册</a></li>--%>
<%--                <li class="nav-item"><a class="nav-link" href="#">购物车 (3)</a></li>--%>
<%--            </ul>--%>
<%--        </div>--%>
<%--    </div>--%>
<%--</nav>--%>

<div class="cart-container">
    <div class="cart-items">
        <c:if test="${not empty cartItems}">
            <!-- 全选和批量删除按钮 -->
            <div class="d-flex justify-content-between mb-3">
                <div>
                    <input type="checkbox" id="selectAll" class="form-check-input me-2">
                    <label for="selectAll">全选</label>
                </div>
                <button id="batchDeleteButton" class="btn btn-danger btn-sm">批量删除</button>
            </div>
            <c:forEach var="item" items="${cartItems}">
                <div class="cart-item d-flex align-items-start mb-3 border-bottom pb-3">
                    <!-- 商品选择框 -->
                    <input type="checkbox" name="cartItem" value="${item.cartId}" class="form-check-input me-3" data-price="${item.price}" data-quantity="${item.quantity}" >
                    <!-- 商品图片 -->
                    <div class="me-3">
                        <img src="${item.image}" alt="${item.productName}" style="width: 100px; height: 100px; object-fit: cover;">
                    </div>
                    <!-- 商品详细信息 -->
                    <div class="flex-grow-1">
                        <!-- 产品名字 -->
                        <p class="cart-item-title fw-bold">${item.productName}</p>
                        <!-- 产品描述 -->
                        <p class="cart-item-description text-muted">${item.productDescription}</p>
                        <!-- 单价 -->
                        <p class="cart-item-price text-danger">单价：¥${item.price}</p>
                        <!-- 数量调整 -->
                        <div class="d-flex align-items-center">
                            <button class="btn btn-outline-secondary btn-sm me-2" onclick="updateQuantity('${item.cartId}', -1)">-</button>
                            <input type="text" class="form-control text-center me-2" style="width: 60px;" value="${item.quantity}" readonly>
                            <button class="btn btn-outline-secondary btn-sm" onclick="updateQuantity('${item.cartId}', 1)">+</button>
                        </div>
                    </div>
                    <!-- 操作按钮 -->
                    <div class="text-end ms-3">
                        <button class="btn btn-link text-secondary" onclick="moveToFavorites('${item.cartId}')">移入收藏夹</button>
                        <button class="btn btn-link text-danger" onclick="deleteItem('${item.cartId}')">删除</button>
                    </div>
                </div>
            </c:forEach>
        </c:if>
        <c:if test="${empty cartItems}">
            <p class="text-center">您的购物车为空。</p>
        </c:if>
    </div>

    <div class="cart-summary">
        <h5>结算明细</h5>
        <p>商品总价：<span>¥${empty cartItems ? 0 : totalPrice}</span></p>
        <p>运费：<span>¥${empty cartItems ? 0 : shippingFee}</span></p>
        <h6>应付金额：<span class="text-danger">¥${empty cartItems ? 0 : payableAmount}</span></h6>
        <form action="/CartServlet" method="post">
            <input type="hidden" name="action" value="checkout">
            <button type="submit" class="btn btn-checkout" ${empty cartItems ? 'disabled' : ''}>去结算</button>
        </form>
    </div>
</div>

<script>
    /**
     * 更新商品数量
     */
    function updateQuantity(itemId, delta) {
        const params = new URLSearchParams();
        params.append('action', 'updateQuantity');
        params.append('itemId', itemId);
        params.append('delta', delta);

        fetch('/CartServlet', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: params.toString()
        })
        .then(response => {
            if (response.ok) {
                location.reload();
            } else {
                alert("更新商品数量失败！");
            }
        })
        .catch(error => {
            console.error(error);
            alert("网络错误，请稍后再试！");
        });
    }

    /**
     * 删除单个商品
     */
    function deleteItem(itemId) {
        if (!confirm("确定删除该商品吗？")) return;

        const params = new URLSearchParams();
        params.append('action', 'deleteItem');
        params.append('itemId', itemId);

        fetch('/CartServlet', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: params.toString()
        })
        .then(response => {
            if (response.ok) {
                location.reload();
            } else {
                alert("删除商品失败！");
            }
        })
        .catch(error => {
            console.error(error);
            alert("网络错误，请稍后再试！");
        });
    }

    /**
     * 批量删除商品
     */
    function batchDeleteItems(itemIds) {
        if (itemIds.length === 0) {
            alert("请选择要删除的商品！");
            return;
        }
        if (!confirm("确定批量删除选中的商品吗？")) return;

        const params = new URLSearchParams();
        params.append('action', 'batchDeleteItems');

        // 确保每个 itemId 都被添加为单独的参数
        itemIds.forEach(itemId => {
            params.append('itemIds', itemId);
        });

        fetch('/CartServlet', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: params.toString()
        })
        .then(response => {
            return response.json();
        })
        .then(data => {
            if (data.status === 'success') {
                location.reload();
            } else {
                alert("批量删除失败！");
            }
        })
        .catch(error => {
            console.error(error);
            alert("网络错误，请稍后再试！");
        });
    }


    // 更新全选框状态
    function updateSelectAllStatus() {
        const checkboxes = document.querySelectorAll('input[name="cartItem"]');
        const selectAllCheckbox = document.querySelector('#selectAll');
        selectAllCheckbox.checked = Array.from(checkboxes).every(checkbox => checkbox.checked);
    }

    // 全选框事件监听
    document.querySelector('#selectAll').addEventListener('change', function () {
        const checkboxes = document.querySelectorAll('input[name="cartItem"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });

    // 每个商品的选择框事件监听
    document.querySelectorAll('input[name="cartItem"]').forEach(checkbox => {
        checkbox.addEventListener('change', updateSelectAllStatus);
    });

    // 初次加载时检查全选状态
    updateSelectAllStatus();

    /**
     * 获取选中的商品ID
     */
    function getSelectedItems() {
        const selectedCheckboxes = document.querySelectorAll('input[name="cartItem"]:checked');
        return Array.from(selectedCheckboxes).map(checkbox => parseInt(checkbox.value, 10));
    }

    /**
     * 批量删除按钮事件
     */
    document.querySelector('#batchDeleteButton').addEventListener('click', function () {
        const selectedItems = getSelectedItems();
        batchDeleteItems(selectedItems);
    });


</script>

</body>
</html>
